//
//  DownLoadUtils.m
//  LobbyGame
//
//  Created by Bad on 2018/5/2.
//  Copyright © 2018年 boxian. All rights reserved.
//

#import "DownLoadUtils.h"
#import "AFNetworking.h"

@implementation DownLoadUtils

+ (NSURLSessionDownloadTask *)downloadWithURL:(NSString *)url
                                     toFilePath:(NSString *)toFilePath
                                     fileName:(NSString *)fileName
                                     progress:(void (^)(NSProgress *downloadProgress))progress
                            completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {

    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    request.timeoutInterval = 50;
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] init];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:progress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *trueFileName = fileName;
        if (!trueFileName) {
            trueFileName = response.suggestedFilename;
        }
        NSString *trueFilePath = [toFilePath stringByAppendingPathComponent:trueFileName];
        return [NSURL fileURLWithPath:trueFilePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        completionHandler(response, filePath, error);
    }];
    
    [task resume];
    
    return task;
}

+ (NSURLSessionDownloadTask *)resumeData:(NSData *)data
                                toFilePath:(NSString *)toFilePath
                                progress:(void (^)(NSProgress *downloadProgress))progress
                       completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {
    
    NSURLSessionDownloadTask *task = [[AFHTTPSessionManager manager] downloadTaskWithResumeData:data progress:progress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        
        NSString *fileName = response.suggestedFilename;
        NSString *trueFilePath = [toFilePath stringByAppendingPathComponent:fileName];
        return [NSURL fileURLWithPath:trueFilePath];
        
    } completionHandler:completionHandler];
    [task resume];
    
    return task;
}

@end
